<script setup>
import {
  Edit,
  Delete
} from '@element-plus/icons-vue'

import { ref } from 'vue'
import { getSysUserListService,updateSysUserService,deleteSysUserService } from '@/api/system/user.js'
import {Plus} from '@element-plus/icons-vue'
import {useTokenStore} from '@/stores/token.js'
import {ElMessage, ElMessageBox} from "element-plus";
import dayjs from 'dayjs'


const tokenStore=useTokenStore()
//用户列表数据模型
const users = ref([])
//请求参数
const params=ref({
  pageNum:1,//当前页
  pageSize:5,//每页条数
  id:null,
  username:null,
  nickname:null,
  email:null,
  createTime:null
})
//用户数据
const userData=ref({
  username:'',
  nickname:'',
  email:'',
  userPic:'',
  createTime:''
})
//总条数
const total = ref(20)
//控制图片放大框
const dialogVisible=ref(false)
//当前放大图片地址
const currentImage=ref('')
//控制抽屉是否显示
const visibleDrawer = ref(false)
//抽屉标题
const title=ref('')
//搜索表单引用
const queryForm=ref()


//显示图片放大框
const showImageDialog=(imageUrl)=>{
  dialogVisible.value=true
  currentImage.value=imageUrl
}

//日期格式化
const formatDate=(date)=>{
  let today = new Date();
  let target = new Date(date)
  if(target.getFullYear()===today.getFullYear()
      &&target.getMonth()===today.getMonth()
      &&target.getDate()===today.getDate()){
    return dayjs(date).format('HH:mm')
  }else {
    return dayjs(date).format('YYYY-MM-DD')
  }
}

//当每页条数发生了变化，调用此函数
const onSizeChange = (size) => {
  params.value.pageSize = size
  userList()
}

//当前页码发生变化，调用此函数
const onCurrentChange = (num) => {
  params.value.pageNum = num
  userList()
}

//查询用户列表
const userList= async ()=>{
  let result= await getSysUserListService(params.value)
  users.value=result.data.items
  total.value=result.data.total
}
userList()

//重置查询表单
const resetQuery=()=>{
  queryForm.value.resetFields()
  userList()
}

//上传图片成功的回调
const uploadSuccess=(result)=>{
  userData.value.userPic=result.data
}

//显示编辑用户抽屉
const showDrawer=(row)=>{
  visibleDrawer.value=true
  title.value='修改用户'
  userData.value.username=row.username
  userData.value.nickname=row.nickname
  userData.value.email=row.email
  userData.value.userPic=row.userPic
  userData.value.createTime=row.createTime
  //扩展用户id属性
  userData.value.id=row.id
}

//修改用户
const updateUser= async ()=>{
  await updateSysUserService(userData.value)
  ElMessage.success("修改成功")
  visibleDrawer.value=false
  userList()
}

//删除用户
const deleteUser= (row)=>{
  ElMessageBox.confirm(
      '你确定要删除该用户吗?',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
  )
      .then( async () => {
        await deleteSysUserService(row.id)
        ElMessage({
          type: 'success',
          message: '删除成功',
        })
        //刷新列表
        userList()
      })
      .catch(() => {
        ElMessage({
          type: 'info',
          message: '取消删除',
        })
      })
}
</script>

<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>后台用户管理</span>
      </div>
    </template>
    <!-- 搜索表单 -->
    <el-form :model="params" ref="queryForm" inline >
      <el-form-item label="用户id：" style="width: 300px" prop="id">
        <el-input v-model="params.id" placeholder="请输入用户id"></el-input>
      </el-form-item>
      <el-form-item label="用户名：" style="width: 300px" prop="username">
        <el-input v-model="params.username" placeholder="请输入用户名"></el-input>
      </el-form-item>
      <el-form-item label="昵称：" style="width: 300px" prop="nickname">
        <el-input v-model="params.nickname" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="邮箱：" style="width: 300px" prop="email">
        <el-input v-model="params.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="创建时间：" style="width: 300px" prop="createTime">
        <el-date-picker
            clearable
            v-model="params.createTime"
            type="date"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
            size="default"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="userList">搜索</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 用户列表 -->
    <el-table :data="users" style="width: 100%">
      <el-table-column label="用户id" align="center" prop="id"></el-table-column>
      <el-table-column label="用户名" align="center" prop="username"></el-table-column>
      <el-table-column label="昵称" align="center" prop="nickname"></el-table-column>
      <el-table-column label="头像" align="center" prop="userPic" >
        <template #default="{ row }">
          <img :src="row.userPic" style="width: 75px; height: 100px" @click="showImageDialog(row.userPic)"/>
        </template>
      </el-table-column>
      <el-table-column label="邮箱" align="center" prop="email"></el-table-column>
      <el-table-column label="创建时间" align="center" prop="createTime">
        <template #default="{ row }">
          <span> {{formatDate(row.createTime)}} </span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="{ row }">
          <el-button :icon="Edit" circle plain type="primary" @click="showDrawer(row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="deleteUser(row)"></el-button>
        </template>
      </el-table-column>
      <template #empty>
        <el-empty description="没有数据" />
      </template>
    </el-table>
    <!-- 分页条 -->
    <el-pagination v-model:current-page="params.pageNum"
                   v-model:page-size="params.pageSize"
                   :page-sizes="[3, 5 ,10, 20]"
                   layout="jumper, total, sizes, prev, pager, next"
                   background
                   :total="total"
                   @size-change="onSizeChange"
                   @current-change="onCurrentChange"
                   style="margin-top: 20px; justify-content: flex-end" />
  </el-card>
  <!-- 图片放大的对话框 -->
  <el-dialog v-model="dialogVisible" title="图片展示" center width="50%">
    <el-image :src="currentImage" style="width: 100%;height: auto"></el-image>
    <el-footer align="center">
        <el-button @click="dialogVisible=false" style="margin-top: 10px">关闭</el-button>
    </el-footer>
  </el-dialog>
  <!-- 抽屉 -->
  <el-drawer v-model="visibleDrawer" :title="title" direction="rtl" size="50%">
    <!-- 修改用户表单 -->
    <el-form :model="userData" label-width="100px" >
      <el-form-item label="用户名" >
        <el-input v-model="userData.username" disabled></el-input>
      </el-form-item>
      <el-form-item label="昵称" >
        <el-input v-model="userData.nickname" placeholder="请输入昵称"></el-input>
      </el-form-item>
      <el-form-item label="邮箱" >
        <el-input v-model="userData.email" placeholder="请输入邮箱"></el-input>
      </el-form-item>
      <el-form-item label="头像">
        <!--
        el-upload自动会发送ajax请求
        auto-upload:是否自动上传
        action:指定请求后台的url
        name:指定上传文件字段名
        headers:指定请求的请求头
        onSuccess:上传成功的回调
        -->
        <el-upload class="avatar-uploader" :auto-upload="true" :show-file-list="false"
                   action="/api/upload" name="file" :headers="{'Authorization':tokenStore.token}"
                   :on-success="uploadSuccess">
          <img v-if="userData.userPic" :src="userData.userPic" class="avatar" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item label="创建时间" >
        <el-input v-model="userData.createTime" disabled></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="updateUser">确定</el-button>
        <el-button type="info" @click="visibleDrawer=false">取消</el-button>
      </el-form-item>
    </el-form>
  </el-drawer>
</template>

<style lang="scss" scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;

  .header {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
}
/* 抽屉样式 */
.avatar-uploader {
  :deep {
    .avatar {
      width: 178px;
      height: 178px;
      display: block;
    }

    .el-upload {
      border: 1px dashed var(--el-border-color);
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: var(--el-transition-duration-fast);
    }

    .el-upload:hover {
      border-color: var(--el-color-primary);
    }

    .el-icon.avatar-uploader-icon {
      font-size: 28px;
      color: #8c939d;
      width: 178px;
      height: 178px;
      text-align: center;
    }
  }
}
.editor {
  width: 100%;
  :deep(.ql-editor) {
    min-height: 200px;
  }
}
</style>